package com.mblog.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class CreateHTML {
	
	public static void crateHTML(ServletContext context,Map<String,Object> data,String templatePath,String targetHtmlPath){  
		Configuration freemarkerCfg = new Configuration();  
		//加载模版  
		freemarkerCfg.setServletContextForTemplateLoading(context, "WEB-INF/mypage/view"); //模板所在路径 
		freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");  
		try {  
		    //指定模版路径  
		    Template template = freemarkerCfg.getTemplate(templatePath,"UTF-8");  
		    template.setEncoding("UTF-8");  
		    //静态页面路径  
		    String htmlPath = context.getRealPath("/view")+"/"+targetHtmlPath;  
		    File htmlFile = new File(htmlPath); 
		    if(!htmlFile.exists()){
		    	htmlFile.createNewFile();
		    } 
		          Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));  
		          //处理模版 加数据加载到模板上并生成html页面
		          template.process(data, out);  
		          out.flush();  
		          out.close();  
		} catch (Exception e) {  
		    e.printStackTrace();  
		}  
	}
}
